package com.xie.wechat;

import android.annotation.SuppressLint;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.NoSuchAlgorithmException;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;

public class UrlUtils {

    /**
     * 获取图片存储路径及名称
     *
     * @param url url
     * @return 文件名
     */
    private static String getFilenameFromUrl(String url) {
        if (url == null || url.length() == 0) {
            return null;
        }
        String[] strList = url.split("\\?");
        if (strList[0] != null) {
            String[] itemList = strList[0].split("/");
            if (itemList.length > 0) {
                return itemList[itemList.length - 1];
            }
        }
        return null;
    }

    /**
     * 获取http url的数据流
     *
     * @param httpUrl url地址
     * @return 数据流
     */
    private static InputStream getStreamByHttpUrl(String httpUrl) {
        InputStream inputStream = null;
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setConnectTimeout(3000);
            urlConnection.setDoInput(true);
            urlConnection.connect();
            int responseCode = urlConnection.getResponseCode();
            if (responseCode == 200) {
                inputStream = urlConnection.getInputStream();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    /**
     * 获取https url的数据流
     *
     * @param httpsUrl url地址
     * @return 数据流
     */
    private static InputStream getStreamByHttpsUrl(String httpsUrl) {
        InputStream inputStream = null;
        try {
            URL url = new URL(httpsUrl);
            HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setConnectTimeout(3000);
            urlConnection.setSSLSocketFactory(SSLContext.getDefault().getSocketFactory());
            //解决由于服务器证书问题导致HTTPS无法访问的情况
            urlConnection.setHostnameVerifier(new HostnameVerifier() {
                @SuppressLint("BadHostnameVerifier")
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            urlConnection.setDoInput(true);
            urlConnection.connect();
            int responseCode = urlConnection.getResponseCode();
            if (responseCode == 200) {
                inputStream = urlConnection.getInputStream();
            }
        } catch (IOException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    /**
     * 存储url图片文件
     *
     * @param imgUrl 图片url
     * @return 文件名称
     */
    public static String getImageByUrl(String imgUrl, String path) {
        try {
            InputStream inputStream;
            URL url = new URL(imgUrl);
            if (url.getProtocol().toLowerCase().equals("https")) {
                inputStream = getStreamByHttpsUrl(imgUrl);
            } else {
                inputStream = getStreamByHttpUrl(imgUrl);
            }
            if (inputStream == null) {
                Log.e("UrlUtils", "[getImageByUrl] inputStream is null.");
                return null;
            }

            String filename = getFilenameFromUrl(imgUrl);
            String filePath = path + "/" + filename;
            File file = new File(filePath);
            FileOutputStream fos = new FileOutputStream(file);

            byte[] buffer = new byte[1500];
            int readlen;
            while ((readlen = inputStream.read(buffer, 0, buffer.length)) >= 0) {
                fos.write(buffer, 0, readlen);
            }
            fos.flush();
            fos.close();
            inputStream.close();

            Log.e("UrlUtils", "[getImageByUrl] filePath： " + filePath);
            return filePath;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

